package service

import (
	"context"

	"task/models"
	pb "task/pb/dispatch"

	log "github.com/sirupsen/logrus"
	"google.golang.org/protobuf/types/known/emptypb"
)

type dispatchServer struct{}

func (s *dispatchServer) Ping(_ context.Context, _ *emptypb.Empty) (*pb.PingResponse, error) {
	return &pb.PingResponse{Message: "ok"}, nil
}

func (s *dispatchServer) Dispatch(ctx context.Context, req *pb.DispatchRequest) (*pb.DispatchResponse, error) {
	var (
		event DispatchEvent
		err   error
	)
	dispatchEvent := &models.DispatchEvent{
		Event:       req.Event,
		ResourceId:  req.ResourceId,
		DagId:       int(req.DagId),
		ProcessorId: int(req.ProcessorId),
		Result:      req.Result,
	}
	if event, err = getDispatchEvent(req.Event); err != nil {
		return nil, err
	}
	if err = event.Prepare(ctx, dispatchEvent); err != nil {
		log.Errorf("Dispatch event(%+v) prepare error(%v)", dispatchEvent, err)
		return nil, err
	}
	if err = event.Compute(ctx, dispatchEvent); err != nil {
		log.Errorf("Dispatch event(%+v) compute error(%v)", dispatchEvent, err)
		return nil, err
	}
	if err = event.After(ctx, dispatchEvent); err != nil {
		log.Errorf("Dispatch event(%+v) after error(%v)", dispatchEvent, err)
		return nil, err
	}
	return &pb.DispatchResponse{
		ProcessorIdList: dispatchEvent.ExecutorList,
	}, nil
}

// NewDispatchServer new dispatch server.
func NewDispatchServer() *dispatchServer {
	return &dispatchServer{}
}
